<?php


namespace App\Libraries;


class RSA
{
    /**
     * var array $_config 密钥对(公钥&私钥)
     */
    private static $config = [
        'public_key' => '',
        'private_key' => '',
    ];

    /**
     * @title 初始配置
     */
    public static function _init($private_key_filepath, $public_key_filepath) {
        self::$config['private_key'] = self::_getContents($private_key_filepath);
        self::$config['public_key'] = self::_getContents($public_key_filepath);
    }

    /**
     * @title 获取文件内容
     * @param $file_path string
     * @return bool|string
     */
    private static function _getContents($file_path) {
        file_exists($file_path) or die ('the file path of the key or public key is incorrect');
        return file_get_contents($file_path);
    }

    /**
     * @title 获取私钥
     * @return bool|resource
     */
    private static function _getPrivateKey() {
        $priv_key = self::$config['private_key'];
        return openssl_pkey_get_private($priv_key);
    }

    /**
     * @title 获取公钥
     * @return bool|resource
     */
    private static function _getPublicKey() {
        $public_key = self::$config['public_key'];
        return openssl_pkey_get_public($public_key);
    }

    /**
     * @title 私钥加密
     * @param string $data
     * @return null|string
     */
    public static function privateEncrypt($data = '') {
        if (!is_string($data)) {
            return null;
        }
        return openssl_private_encrypt($data, $encrypted, self::_getPrivateKey()) ? base64_encode($encrypted) : null;
    }

    /**
     * @title 公钥加密
     * @param string $data
     * @return null|string
     */
    public static function publicEncrypt($data = '') {
        if (!is_string($data)) {
            return null;
        }
        return openssl_public_encrypt($data, $encrypted, self::_getPublicKey()) ? base64_encode($encrypted) : null;
    }

    /**
     * @title 私钥解密
     * @param string $encrypted
     * @return null
     */
    public static function privateDecrypt($encrypted = '') {
        if (!is_string($encrypted)) {
            return null;
        }
        return (openssl_private_decrypt(base64_decode($encrypted), $decrypted, self::_getPrivateKey())) ? $decrypted : null;
    }

    /**
     * @title 公钥解密
     * @param string $encrypted
     * @return null
     */
    public static function publicDecrypt($encrypted = '') {
        if (!is_string($encrypted)) {
            return null;
        }
        return (openssl_public_decrypt(base64_decode($encrypted), $decrypted, self::_getPublicKey())) ? $decrypted : null;
    }
}